﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using DTO;

namespace BLL
{
    public class LotBLL
    {
        private static int lotID = 0;
        GaraDataContext DB = new GaraDataContext();

        public IQueryable SelectAll()
        {
            return (from p in DB.Lots
                    join f in DB.Floors
                    on p.FloorID equals f.FloorID into result
                    from li in result.DefaultIfEmpty()
                    select new
                    {
                        p.LotID,
                        li.NumberFloor,
                        p.NumberLot,
                        p.Status
                    }).AsQueryable();
        }

        public string Insert(LotDTO lotDTO)
        {
            try
            {
                Lot lot = new Lot();
                lot.LotID = (lotID++).ToString();
                lot.FloorID = lotDTO.FloorID;
                lot.NumberLot = lotDTO.NumberLot;
                lot.Status = lotDTO.Status;

                DB.Lots.InsertOnSubmit(lot);
                DB.SubmitChanges();
                return MessageAction.Success;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string Update(LotDTO lotDTO)
        {
            try
            {
                Lot lot = DB.Lots.Where(s => s.LotID == lotDTO.LotID).FirstOrDefault();
                lot.FloorID = lotDTO.FloorID;
                lot.NumberLot = lotDTO.NumberLot;
                lot.Status = lotDTO.Status;

                DB.SubmitChanges();
                return MessageAction.Success;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public Boolean CheckLotExist(int numberFloor, int numberLot)
        {
            int count = (from p in DB.Lots
                         join f in DB.Floors
                             on p.FloorID equals f.FloorID into result
                         from li in result.DefaultIfEmpty()
                         where li.NumberFloor == numberFloor && p.NumberLot == numberLot
                         select new
                         {
                             p.LotID
                         }
                             ).Distinct().Count();
            if (count > 0) return true;
            else return false;
        }
    }
}
